package com.sys.app.entity.config;


import com.baomidou.mybatisplus.annotation.IEnum;
import com.sys.app.entity.IBaseEnum;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;


public class MybatisEnumTypeHandler  <E extends IBaseEnum> extends BaseTypeHandler<E> {
    private static Logger logger = LoggerFactory.getLogger(MybatisEnumTypeHandler.class);
    private Class<E> type;
    private E[] enums;

    public MybatisEnumTypeHandler(){}
    public MybatisEnumTypeHandler(Class<E> type){
        this.type = type;
        this.enums = type.getEnumConstants();
    }

    @Override
    public void setNonNullParameter(PreparedStatement preparedStatement, int i, IBaseEnum keyValueEnum, JdbcType jdbcType) throws SQLException {
        preparedStatement.setInt(i, keyValueEnum.getValue().intValue());
    }

    @Override
    public E getNullableResult(ResultSet resultSet, int i) throws SQLException {
        return getEnum(resultSet.getInt(i));
    }

    @Override
    public E getNullableResult(ResultSet resultSet, String s) throws SQLException {
        return getEnum(resultSet.getInt(s));
    }

    @Override
    public E getNullableResult(CallableStatement callableStatement, int i) throws SQLException {
        return getEnum(callableStatement.getInt(i));
    }

    private E getEnum(int value){
        for (E keyValue: enums) {
            if (keyValue.getValue().intValue()==value){
                return keyValue;
            }
        }
        return null;
    }

}